<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import { Message } from 'element-ui'
import { getProjectInventoryList } from '@/api/project-update/project-inventory'

const props = defineProps({
  status: String,
  regionId: String,
  regionList: Array,
})

const tableData = ref([
  {
    num: '投资（万元）',
    projectId: '',
  },
  {
    num: '拆除建筑面积（m²）',
  },
  {
    num: '改造建筑面积（m²）',
  },
  {
    num: '新建建筑面积（m²）',
  },
])

// 合并单元格
const spanMethod = ({ rowIndex, columnIndex }) => {
  // 合并行 -- 除余匹配行
  if (columnIndex < 4 || columnIndex > 9) {
    if (rowIndex % 4 === 0) {
      return [4, 1]
    } else {
      return [0, 0]
    }
  }
}

const handleAddClick = () => {
  tableData.value.push(
    {
      num: '投资（万元）',
      projectId: '',
    },
    {
      num: '拆除建筑面积（m²）',
    },
    {
      num: '改造建筑面积（m²）',
    },
    {
      num: '新建建筑面积（m²）',
    }
  )
}

const handleDeleteCLick = () => {
  // console.log(tableData.value)
  const finds = tableData.value.filter((item) => item.checked)
  if (finds.length === 0) {
    Message.warning('请选择要删除的数据')
    return
  }
  finds.forEach((item) => {
    const index = tableData.value.indexOf(item)
    tableData.value.splice(index, 4)
  })
}

const planTypeList = ref([
  { label: '储备阶段', value: 'reserve' },
  { label: '实施阶段', value: 'implement' },
  { label: '运营阶段', value: 'manage' },
])

const projectNameList = ref([])

const getTotalValue = (row: any) => {
  let num1 = row.num1 ? Number(row.num1) : 0
  let num2 = row.num2 ? Number(row.num2) : 0
  let num3 = row.num3 ? Number(row.num3) : 0
  let num4 = row.num4 ? Number(row.num4) : 0
  return num1 + num2 + num3 + num4
}

const inputData = (data) => {
  tableData.value = []
  for (let i = 0, len = data.length; i < len; i++) {
    tableData.value.push({
      ...data[i],
      num: '投资（万元）',
      num1: data[i].investmentOne,
      num2: data[i].investmentTwo,
      num3: data[i].investmentThree,
      num4: data[i].investmentFour,
    })
    tableData.value.push({
      num: '拆除建筑面积（m²）',
      num1: data[i].dismantleOne,
      num2: data[i].dismantleTwo,
      num3: data[i].dismantleThree,
      num4: data[i].dismantleFour,
    })
    tableData.value.push({
      num: '改造建筑面积（m²）',
      num1: data[i].changeOne,
      num2: data[i].changeTwo,
      num3: data[i].changeThree,
      num4: data[i].changeFour,
    })
    tableData.value.push({
      num: '新建建筑面积（m²）',
      num1: data[i].newOne,
      num2: data[i].newTwo,
      num3: data[i].newThree,
      num4: data[i].newFour,
    })
  }
}

const getSubmitData = () => {
  const resultArr = []
  for (let i = 0, len = tableData.value.length; i < len; i += 4) {
    const current = tableData.value[i]
    resultArr.push({
      ...current,
      investmentOne: current.num1,
      investmentTwo: current.num2,
      investmentThree: current.num3,
      investmentFour: current.num4,
      dismantleOne: tableData.value[i + 1].num1,
      dismantleTwo: tableData.value[i + 1].num2,
      dismantleThree: tableData.value[i + 1].num3,
      dismantleFour: tableData.value[i + 1].num4,
      changeOne: tableData.value[i + 2].num1,
      changeTwo: tableData.value[i + 2].num2,
      changeThree: tableData.value[i + 2].num3,
      changeFour: tableData.value[i + 2].num4,
      newOne: tableData.value[i + 3].num1,
      newTwo: tableData.value[i + 3].num2,
      newThree: tableData.value[i + 3].num3,
      newFour: tableData.value[i + 3].num4,
    })
  }
  return resultArr
}

const handleChangePlanType = (row) => {
  row.projectId = ''
}

const handleVisibleChange = (value, row) => {
  if (value) {
    if (!props.regionId) {
      Message.warning('请先选择区域后重试！')
    }
    if (!row.projectType) {
      Message.warning('请先选择项目分类后重试！')
    }
  }
}

const getAllProjectNameList = () => {
  getProjectInventoryList({ pageSize: 999 }).then((res) => {
    if (res.success) {
      projectNameList.value = res.data.list
    }
  })
}

const getProjectNameList = (projectType) => {
  if (!props.regionId || !projectType) {
    return []
  }
  const regionName = props.regionList.find(
    (item) => item.pkid === props.regionId
  )?.areaName
  return projectNameList.value
    .filter(
      (item) => item.peStage === projectType && item.district === regionName
    )
    .map((item) => ({
      label: item.peName,
      value: item.id,
    }))
}

onMounted(() => {
  getAllProjectNameList()
})

defineExpose({
  inputData,
  getSubmitData,
})
</script>

<template>
  <div class="fill-table">
    <div class="fill-buttons">
      <template v-if="!status">
        <el-button type="text" @click="handleAddClick">
          <i
            class="el-icon-circle-plus-outline"
            style="font-size: 16px; margin-right: 6px"
          ></i
          >新增
        </el-button>
        <el-button class="danger-color" type="text" @click="handleDeleteCLick">
          <i
            class="el-icon-delete"
            style="font-size: 16px; margin-right: 6px"
          ></i
          >删除
        </el-button>
      </template>
    </div>
    <el-table :data="tableData" border :span-method="spanMethod">
      <el-table-column prop="num" label="序号" width="60px">
        <template #default="scope">
          <el-checkbox
            v-model="scope.row.checked"
            :disabled="!!status"
          ></el-checkbox>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="项目分类">
        <template #default="scope">
          <el-select
            v-model="scope.row.projectType"
            placeholder="请选择"
            clearable
            :disabled="!!status"
            @change="handleChangePlanType(scope.row)"
          >
            <el-option
              v-for="(item, index) in planTypeList"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="项目名称">
        <template #default="scope">
          <el-select
            v-model="scope.row.projectId"
            placeholder="请选择"
            clearable
            :disabled="!!status"
            filterable
            @visible-change="(e) => handleVisibleChange(e, scope.row)"
          >
            <el-option
              v-for="(item, index) in getProjectNameList(scope.row.projectType)"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="更新内容">
        <template #default="scope">
          <el-input
            :disabled="!!status"
            v-model="scope.row.updateContent"
            type="textarea"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="target" label="更新项目安排" :align="'center'">
        <el-table-column prop="target" label="序号" width="155px">
          <template #default="scope">
            {{ scope.row.num }}
          </template>
        </el-table-column>
        <el-table-column prop="target" label="一季度">
          <template #default="scope">
            <el-input
              v-model="scope.row.num1"
              type="number"
              :disabled="!!status"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="target" label="二季度">
          <template #default="scope">
            <el-input
              v-model="scope.row.num2"
              type="number"
              :disabled="!!status"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="target" label="三季度">
          <template #default="scope">
            <el-input
              v-model="scope.row.num3"
              type="number"
              :disabled="!!status"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="target" label="四季度">
          <template #default="scope">
            <el-input
              v-model="scope.row.num4"
              type="number"
              :disabled="!!status"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="合计" prop="total">
          <template #default="scope">
            {{ getTotalValue(scope.row) }}
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column prop="target" label="2024年更新计划（必须按照季度填报）">
        <template #default="scope">
          <el-input
            v-model="scope.row.updatePlan"
            placeholder="请输入"
            type="textarea"
            :disabled="!!status"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注">
        <template #default="scope">
          <el-input
            v-model="scope.row.remark"
            placeholder="请输入"
            type="textarea"
            :disabled="!!status"
          ></el-input>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style scoped lang="scss">
.fill-table {
  position: relative;

  .fill-buttons {
    position: absolute;
    top: -40px;
    right: 16px;

    .danger-color {
      color: #f78989;
    }
  }
}
</style>
